/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.vidmt.api.modules.sys.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import com.vidmt.api.common.jee.ValidateCodeServlet;
import com.vidmt.api.modules.sys.Acc;
import com.vidmt.api.modules.sys.Enums.AccType;
import com.vidmt.api.modules.sys.entity.User;
import com.vidmt.api.modules.sys.service.UserService;

/**
 * 系统安全认证实现类
 * 
 * @author ThinkGem
 * @version 2014-7-5
 */
@Service
// @DependsOn({"userDao","roleDao","menuDao"})
public class MyWebRealm extends AuthorizingRealm {

	private Logger logger = LoggerFactory.getLogger(getClass());
	private static String adminName = Global.getConfig("admin.adminName");
	private static String adminPwd = Global.getConfig("admin.adminPassword");

//	@Autowired
//	private SystemService systemService;
	@Autowired
	private UserService userService;
	
	@Override
	public boolean supports(AuthenticationToken token) {
		return token != null && MyWebToken.class.isAssignableFrom(token.getClass());
	}

	public MyWebRealm() {
		super(new MyCredentialMather());
	}

	/**
	 * 认证回调函数, 登录时调用
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) {
		MyWebToken token = (MyWebToken) authcToken;
		// 校验登录验证码
		if (UserUtils.isValidateCodeLogin(token.getUsername(), false, false)) {
			Session session = UserUtils.getSession();
			String code = (String) session.getAttribute(ValidateCodeServlet.VALIDATE_CODE);
			if (token.getCaptcha() == null || !token.getCaptcha().toUpperCase().equals(code)) {
				throw new AuthenticationException("msg:验证码错误, 请重试.");
			}
		}

		// 校验用户名密码
		if (adminName.equals(authcToken.getPrincipal())) {
			User user = new User();
			user.setName(adminName);
			return new SimpleAuthenticationInfo(new MyPrincipal(user), adminPwd, getName());
		} else {
			String principal = (String) authcToken.getPrincipal();
			if (!principal.matches("^[1-9]\\d{10}$")) {
				return null;
			}
			Acc acc = new Acc(AccType.phone, (String) authcToken.getPrincipal());
			User user = null;
			if (acc.type() == AccType.uid) {
				user = userService.load(Long.valueOf(acc.value()));
			} else {
				user = userService.findByAcc(acc);
			}
			String pwd = userService.getPwd(user.getId());

			return new SimpleAuthenticationInfo(new MyPrincipal(user), pwd, getName());
		}
	}

	/**
	 * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		Object principal = getAvailablePrincipal(principals);
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		MyPrincipal mp = (MyPrincipal) principal;
		User user = mp.getUser();
		if(user.isAdmin()){
			info.addStringPermission("sys");
		}
		// List<Menu> list = UserUtils.getAllMenuList();
		// for (Menu menu : list) {
		// if (StringUtils.isNotBlank(menu.getPermission())) {
		// // 添加基于Permission的权限信息
		// for (String permission : StringUtils.split(menu.getPermission(),
		// ",")) {
		// info.addStringPermission(permission);
		// }
		// }
		// }
		// info.addRole("admin");
		// 添加用户权限
		info.addStringPermission("sys");
		info.addStringPermission("user");
		return info;
	}
}
